#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "const.h"

static charge_fee_cfg_t a_fee_cfg[20];
static int fee_qt;

int Process(double fee_id);
int Initialize();
char *GetFeeNum(char *fee_type);


int main(int argc, char *argv[])
{
    int times, count;
    double fee_id;
    time_t start, end;

    if(argc!=2)  times=30000;
    else  times=atoi(argv[1]);
    if(times==0)  times=30000;

    if(DbsConnect())  exit(1);

    if(Initialize())
    {   printf("Initialize fail\n");  exit(1);   }

    time(&start); 
    for(count=0; count<times; count++)
    {
        fee_id=(double)(random_int(0,9)*100000+random_int(0,9)*10000+
               random_int(0,9)*1000+random_int(0,9)*100+
               random_int(0,9)*10+random_int(0,9));
        if(Process(fee_id))
        {
            printf("bs_join query %d times fail\n", times);
            exit(1);
        }
/*
        printf("no.%05d fee_id:%.0lf finished\n", count+1, fee_id);
*/
    }
    time(&end);
    printf("time cost total:%d seconds\n", end-start);

    exit(0);
}


int Initialize()
{
    int result;

    fee_qt=0;
    if(DbsCHARGE_FEE_CFG_CUR_List(DBS_OPEN, &a_fee_cfg[fee_qt])!=
           DB_OK)
    {   printf("open cursor fail\n");  return -1;   }
    while(1)
    {
        result=DbsCHARGE_FEE_CFG_CUR_List(DBS_FETCH,
                   &a_fee_cfg[fee_qt]);
        if(result!=DB_OK && result!=DB_NOTFOUND)
        {   printf("fetch cursor fail\n");  return -1;   }
        if(result==DB_NOTFOUND)  break;

        trim_space(a_fee_cfg[fee_qt].fee_nm); 
        fee_qt++;
    }
    if(DbsCHARGE_FEE_CFG_CUR_List(DBS_CLOSE, &a_fee_cfg[fee_qt])!=
           DB_OK)
    {   printf("close cursor fail\n");  return -1;   }

    strcpy(a_fee_cfg[fee_qt].fee_type, "FF");
    strcpy(a_fee_cfg[fee_qt].fee_nm, " ");

    return 0;
}


char *GetFeeNum(char *fee_type)
{
    int i;

    for(i=0; i<fee_qt; i++)
        if(!strcmp(a_fee_cfg[i].fee_type, fee_type))  break;
    return(a_fee_cfg[i].fee_nm);
}


int Process(double fee_id)
{
    int result;
    charge_fee_dtl_t ChargeFeeDtl;

    ChargeFeeDtl.fee_id=fee_id;
    if(DbsCHARGE_FEE_DTL_CUR_BSNoJoin(DBS_OPEN, &ChargeFeeDtl)!=DB_OK)
    {   printf("open cursor fail\n");  return -1;   }
    while(1)
    {
        result=DbsCHARGE_FEE_DTL_CUR_BSNoJoin(DBS_FETCH,
                   &ChargeFeeDtl);
        if(result!=DB_OK && result!=DB_NOTFOUND)
        {   printf("fetch cursor fail\n");  return -1;   }
        if(result==DB_NOTFOUND)  break;

        GetFeeNum(ChargeFeeDtl.fee_type);
    }
    if(DbsCHARGE_FEE_DTL_CUR_BSNoJoin(DBS_CLOSE, &ChargeFeeDtl)!=
           DB_OK)
    {   printf("close cursor fail\n");  return -1;   }

    return 0;
}
